package com.muye.dianli.activity;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.mime.content.StringBody;

import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.muye.adapter.ArticleListAdapter;
import com.muye.constant.C;
import com.muye.constant.U;
import com.muye.dianli.BaseActivity;
import com.muye.dianli.R;
import com.muye.field.ArticleListData;
import com.zvezda.algorithm.utils.MD5;
import com.zvezda.http.utils.HttpConst;
import com.zvezda.http.utils.KeyValue;
import com.zvezda.http.utils.RequestHttpListener;
import com.zvezda.http.utils.RequestHttpPostThread;

/**
 * 文章列表页面
 * 
 * @author TangChao
 *
 */
public class ArticleListActivity extends BaseActivity implements OnClickListener, OnKeyListener
{
	/**
	 * 列表
	 */
	private PullToRefreshListView listView;
	
	/**
	 * 请求数据线程
	 */
	private RequestHttpPostThread requestHttpPostThread;
	
	/**
	 * 数据源
	 */
	private List<ArticleListData> arrayList;
	
	/**
	 * 图片缓存路径
	 */
	private String filePath;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		setContentView(R.layout.article_list_layout);
		filePath = C.FILE_PATH + "/DianLi/ArticleList";
		File file = new File(filePath);
		if (!file.exists())
		{
			file.mkdirs();
		}
		createTitle();
		initWidget();
		getArticleList("0", "1", "10");
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}
	
	/**
	 * 初始化标题栏
	 */
	private void createTitle()
	{
		TextView titleName = (TextView) findViewById(R.id.title_bar_name_text_view);
		titleName.setText("文章");
		ImageView titleLeftBtn = (ImageView) findViewById(R.id.title_bar_left_image_view);
		titleLeftBtn.setVisibility(View.VISIBLE);
		titleLeftBtn.setImageResource(R.drawable.title_back_icon);
		titleLeftBtn.setOnClickListener(this);
	}
	
	private void initWidget()
	{
		listView = (PullToRefreshListView) findViewById(R.id.article_list_layout_list_view);
		listView.setOnRefreshListener(new OnRefreshListener<ListView>()
		{
			
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView)
			{
				getArticleList("0", "1", "10");
			}
		});
		listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener()
		{
			
			@Override
			public void onLastItemVisible()
			{
				getArticleList("0", "2", "10");
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener()
		{
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				Intent intent = new Intent(ArticleListActivity.this, ArticleDetailActivity.class);
				intent.putExtra("TITLE_NAME", arrayList.get(arg2 - 1).title);
				intent.putExtra("ID", arrayList.get(arg2 - 1).id);
				startActivity(intent);
			}
		});
	}
	
	/**
	 * 请求文章列表
	 */
	private void getArticleList(String type, String page, String size)
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = C.APPID + page + size + type + C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody(C.APPID, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("page", new StringBody(page, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("size", new StringBody(size, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("type", new StringBody(type, Charset.forName("utf-8"))));
			paramsList
					.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		requestHttpPostThread = new RequestHttpPostThread(getArticleListListener, U.CATEGORY_LIST, paramsList);
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求文章列表返回监听
	 */
	private RequestHttpListener getArticleListListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "请求文章列表结果----->" + str);
					Gson gson = new Gson();
					ArticleListField item = gson.fromJson(str, ArticleListField.class);
					arrayList = item.data;
				}
				catch (UnsupportedEncodingException e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 0;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 处理数据
	 */
	private Handler handler = new Handler()
	{
		
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			listView.onRefreshComplete();
			C.closePragressDialog();
			switch (msg.what)
			{
				case 0:
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							ArticleListAdapter adapter = new ArticleListAdapter(ArticleListActivity.this, arrayList,
									filePath);
							listView.setAdapter(adapter);
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(ArticleListActivity.this, "请求失败,请重试");
							break;
						
						default:
							break;
					}
					break;
				
				default:
					break;
			}
		}
		
	};
	
	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.title_bar_left_image_view:
				finish();
				break;
			
			default:
				break;
		}
	}
	
	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
	{
		// TODO Auto-generated method stub
		return false;
	}
	
}
